#include "thread.h"
#include <assert.h>
#include <log/logger.h>

namespace thread {

	Thread::Thread():
		alive_(false),
		stop_(false),
		thread_id_(0)
	{
		MEMBER_DEBUG_LOG("[+/-]Thread::ctor()");
	}

	Thread::~Thread()
	{
		MEMBER_DEBUG_LOG("[+/-]Thread::dtor()");
	}

	int Thread::Start()
	{
		MEMBER_DEBUG_LOG("[+]Thread::Start()");
		// if create successful, will return 0
		int err = pthread_create(&thread_id_, NULL,
				ThreadProc, (void*)(this));
		MEMBER_LOG(LOG_ERR, "Thread::Start(), err: %d", err);
		MEMBER_DEBUG_LOG("[-]Thread::Start(), err: %d", err);
		return err;
	}

	void* Thread::ThreadProc(void* arg)
	{
		LOG(LOG_INFO, "[+]Thread::ThreadProc");
		assert(arg);
		Thread* self = (Thread*)(arg);
		self->alive_ = true;
		try
		{
			self->Run();
		}
		catch(...)
		{
			LOG(LOG_ERR, "[-]Thread::ThreadProc catch exception, thread id: %d",
					(int)(self->thread_id_));
		}
		self->alive_ = false;
		if (self->release_)
		{
			delete self;
		}
		LOG(LOG_INFO, "[-]Thread::ThreadProc");
		return (void*)(0);
	}

	void Thread::Join()
	{
		MEMBER_DEBUG_LOG("[+]Thread::Join");
		pthread_join(thread_id_, NULL);
		thread_id_ = 0;
		alive_ = false;
		MEMBER_DEBUG_LOG("[-]Thread::Join");
	}

}

